package com.oda.camera;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.oda.camera.util.LoadImage;
import com.oda.camera.util.PathFile;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;




public class UploadService extends Service {
	private PathFile listeImage;
	/**
	 * Le fichier
	 */
	private File fichier;
	private Intent mInvokeIntent;

	private volatile Looper mUploadLooper;

	private volatile ServiceHandler mUploadHandler;
	
	private int check = 0;
	
	/**
	 * The Class service handler
	 * @author zou
	 *
	 */
	public final class ServiceHandler extends Handler{
		public ServiceHandler(Looper looper) {
			super(looper);
		}
		
	
	
	/**
	 * Handle the message	
	 */
	public void handleMessage(Message msg) {
			//get extra datas
			Uri selectedImg = (Uri)msg.obj;
			Log.i(getClass().getSimpleName(),"selectedImg =" + selectedImg);

			//upload the file to the web server
			upload(selectedImg);
			
			
			Log.i(getClass().getSimpleName(), "Message: " + msg);
			Log.i(getClass().getSimpleName(), "Done with #" + msg.arg1);
			stopSelf(msg.arg1);
		}
	};
		
	
	
	// Method called when (an instance of) the Service is created
	public void onCreate() {
		Log.d("Create","Service create");
		
		Log.i(getClass().getSimpleName(),"HttpUploader on create");
		
		// This is who should be launched if the user selects our persistent
		// notification.
		mInvokeIntent = new Intent();
		mInvokeIntent.setClassName("com.oda.camera", "UploadService");

		 /*Start up the thread running the service. Note that we create a
		 separate thread because the service normally runs in the process's
		 main thread, which we don't want to block.*/
		HandlerThread thread = new HandlerThread("UploadService");
		thread.start();

		mUploadLooper = thread.getLooper();
		mUploadHandler = new ServiceHandler(mUploadLooper);
	}
	
	public void onStart(Intent uploadintent, int startId) {
		Log.d("Start", "Service start");
		// recup des data pour envoi via msg dans la msgqueue pour traitement
		Message msg = mUploadHandler.obtainMessage();
		msg.arg1 = startId;
		//on place l'uri reçu dans l'intent dans le msg pour le handler
		msg.obj = uploadintent.getData();
		mUploadHandler.sendMessage(msg);
		Log.d(getClass().getSimpleName(), "Sending: " + msg);

	}
	
	public void upload(Uri uriImage){
		String url="http://192.168.137.26:8080/wsRestImage/rest/colza/upload";
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        
        String[] projection = { MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.DISPLAY_NAME};
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(uriImage, projection, null, null, null);
        String path=c.getString(0);
        Log.e("File", ""+path);
        try {
        	//MultipartEntityBuilder to gather data
        	MultipartEntityBuilder multipartEntity=MultipartEntityBuilder.create();
        	multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        	multipartEntity.addPart("file", new FileBody(new File(path)));
        	
        	httppost.setEntity(multipartEntity.build());
        	
        	HttpResponse reponse=httpclient.execute(httppost);
        	HttpEntity resEntity=reponse.getEntity();
        	
        	BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            Log.i("test", "Response: " + s);
        	
		} catch (Exception er) {
			Log.e("ERROR",""+er);
			check++;
		}

	} 

	

	// Method called when the (instance of) the Service is requested to terminate
	public void onDestroy() {
		mUploadLooper.quit();

		if(check == 0) { //http response contains no error
			Toast.makeText(UploadService.this, "photo envoyée", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(UploadService.this, "échec d'envoi de la photo", Toast.LENGTH_SHORT).show();
		}
		super.onDestroy();
	}


	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
}